<?php

/**
 * ajaxrt()
 * 
 * @return
 */
function ajaxrt($status,$msg,$data=null){//ajax 返回任何ajax请求，包括状态，消息，回传数据

if(isset($data))
$arr = array(array('status' => $status, 'data' => $data, 'msg' => $msg));
else
$arr = array(array('status' => $status, 'msg' => $msg));
$datart = json_encode($arr);

return $datart; 
    
}


//执行action前检查是否有登录session
/**
 * checkLoginSession()
 * 
 * @return
 */
function checkLoginSession()
{
    if (!isset($_SESSION['UserInfo']))
    {
        $url = U('AuthACL/login');
        redirect($url);
        return;
    }
    else
    {
    //setcookie('HAS_SN','' , time() + 3600 * 24 * 7, '/'); //清空历史的cookie
     $uPdo = D('user');
     $user_id = $_SESSION['UserInfo']['login_id']; 
     $ip = trim(get_client_ip());
     setcookie('__IP',$ip , time() + 3600 * 24 * 7, '/');     
     setcookie('__NOW_APP',__SELF__ , time() + 3600 * 24, '/');         
    }   
}

/**
 * checkSec()
 * 
 * @return
 */
function checkSec($sec){//检查是否满足安全权限参数，否则报错
		if($_SESSION['UserInfo']['secLevel']<$sec)
		dump("权限不足，请联系客服确认！");
}

function checkPaySec($paySec)
{
$User = M('User');
$id_user = $_SESSION['UserInfo']['id']; 
$paySec = md5($paySec);
$okpaysec =   $_SESSION['UserInfo']['paySecret']; 
return ($paySec == $okpaysec);    
}

//检查财务权限，todo
/**
 * checkFinance()
 * 
 * @return
 */
function checkFinance()
{
    if (!isset($_SESSION['UserInfo']))
    {
        $url = U('AuthACL/login');
        redirect($url);
        return;
    }
    else
    {
     $uPdo = D('user');
     $user_id = $_SESSION['UserInfo']['login_id']; 
     $ip = trim(get_client_ip());
     setcookie('__IP',$ip , time() + 3600 * 24 * 7, '/');     
     setcookie('__NOW_APP',__SELF__ , time() + 3600 * 24, '/');         
    }   
}


// 获取客户端IP地址
/**
 * get_client_ip()
 * 
 * @return
 */
function get_client_ip(){
   if (getenv("HTTP_CLIENT_IP") && strcasecmp(getenv("HTTP_CLIENT_IP"), "unknown"))
       $ip = getenv("HTTP_CLIENT_IP");
   else if (getenv("HTTP_X_FORWARDED_FOR") && strcasecmp(getenv("HTTP_X_FORWARDED_FOR"), "unknown"))
       $ip = getenv("HTTP_X_FORWARDED_FOR");
   else if (getenv("REMOTE_ADDR") && strcasecmp(getenv("REMOTE_ADDR"), "unknown"))
       $ip = getenv("REMOTE_ADDR");
   else if (isset($_SERVER['REMOTE_ADDR']) && $_SERVER['REMOTE_ADDR'] && strcasecmp($_SERVER['REMOTE_ADDR'], "unknown"))
       $ip = $_SERVER['REMOTE_ADDR'];
   else
       $ip = "unknown";
   return($ip);
}


//显示指定的表名，字段s，排序方式，搜索索引字段分页信息，需要模板配合
/**
 * ShowTable()
 * 
 * @return
 */
function ShowTable($tname, $Field, $Asc, $searchwords,$rowx=NULL)
{
$sd = isset($searchwords)?"1 = 1 and " . $searchwords:' 1=1';

    $tb = D($tname);

    $list_tmp = $tb->query("SELECT count($Field) as count FROM __TABLE__ where $sd");
    $count = $list_tmp[0]["count"];
	//dump($count);
    $listRows = isset($rowx)?$rowx:10;
    $fields = '*';
	import("ORG.Util.SimplePage");
	//$page = new SimplePage($rows, $perpage, $display, $wrap, $parameter);
	$page = new SimplePage($count, $listRows);	
	//dump($page);

    $list = $tb->where($sd)->field($fields)->order($Field.' '.$Asc)
        ->limit("$page->firstRow , $page->listRows")->findall();
    $pages = $page->show();
	//dump($pages);
    $arrayVa['a'] = $list;
    $arrayVa['b'] = $pages;
    return $arrayVa;
}

//多表复杂查询，分页返回结果，最多1个主表+5个表
function ShowTableM($Mtname,$fieldstr,$tb1,$condition1,$ordbyField=NULL,$searchwords=NULL,$tb2=NULL,$condition2=NULL,$tb3=NULL,$condition3=NULL,$tb4=NULL,$condition4=NULL, $tb5=NULL,$condition5=NULL)
{
    $sd = isset($searchwords)? ' 1=1 '. $searchwords:' 1=1';
    //$ordbyField 要有desc asc，例如 id_gezi_prj DESC(DESC是降序排列 ASC是升序)
    $Mdeltb = new Model();
    
    $sqlstr = "	SELECT ".$fieldstr ." FROM ".$Mtname;  
    $sqlstr = isset($tb1)?$sqlstr." JOIN ". $tb1 ." ON ". $condition1:$sqlstr; 
    $sqlstr = isset($tb2)?$sqlstr." JOIN ". $tb2 ." ON ". $condition2:$sqlstr;
    $sqlstr = isset($tb3)?$sqlstr." JOIN ". $tb3 ." ON ". $condition3:$sqlstr;
    $sqlstr = isset($tb4)?$sqlstr." JOIN ". $tb4 ." ON ". $condition4:$sqlstr;
    $sqlstr = isset($tb5)?$sqlstr." JOIN ". $tb5 ." ON ". $condition5:$sqlstr;
    $sqlstr = $sqlstr." WHERE ".$sd;
    $sqlstr = isset($ordbyField)?$sqlstr." ORDER BY ".$ordbyField:$sqlstr;
    //dump($sqlstr);
    $rt = $Mdeltb->query($sqlstr);    
    $arrayVa['a'] = $rt;
    $arrayVa['b'] = count($rt);
    return $arrayVa;
}

//检查登录id所在区域 邮编是否存在团队，存在返回团队编号和团长id，否则返回false

	/**
	 * getZipTeam()
	 * 
	 * @return
	 */
	function getZipTeam(){
	
	$zipcode = $_SESSION['UserInfo']['zip_code'];
	
	$Team = M('Team');
	$tlist = $Team->where("zip_code = '$zipcode'")->findAll();

	return $tlist;
	}

//空函数
  /**
   * doNothing()
   * 
   * @return
   */
  function doNothing()
  {
  return NULL;
  }

//初始化申请页面的数据
  /**
   * init_apply()
   * 
   * @return
   */
  function init_apply(){//管理申请，需要管理员权限
        checkSec(5);
		$tname = 'Msg'; $Field = 'id_gezi_msg'; $Asc = ' ASC'; 
		$searchwords='target ='.'"'. 'system' . '"' . 'and status = '. '"'.'tobeCheck'.'"' ;
		return ShowTable($tname, $Field, $Asc, $searchwords);
  }


//
/**
 * passSaleAuth()
 * 
 * @return
 */
function passSaleAuth($msgid,$id_user)//客服联系卖家，人工验证后手工通过卖家认证，执行这个函数
	{
		$User = M("User");
		$data['secLevel'] = 1;//通过卖家认证				
		$topicid =$User->where("id='$id_user'")->save($data);
		$topicid1 = setMsg($msgid,'OK');
		return 	($topicid AND $topicid1);		
	}
 /**
  * setTmember()
  * 
  * @return
  */
 function setTmember()//客服联系卖家，人工验证后手工通过卖家认证，执行这个函数
	{
		$User = M("User");
		$data['secLevel'] = 2;//通过认证				
		$topicid =$User->where('id='.$_POST['to_auth_id'])->save($data);				
	}
	
 /**
  * setMsg()
  * 
  * @return
  */
 function setMsg($msgid,$status=NULL)//设置此消息
	{
        $Msg = M('Msg');
		$data['status']=isset($status)?$status:'OK';//修改消息状态
        $rt = $Msg->where("id_gezi_msg = '$msgid' ")->save($data);
		return $rt;				
	}	 
 /**
  * checkCharge()
  * 
  * @return
  */
 function checkCharge($msgid,$id_user,$count)//客服手工确认交易是否已经成交，然后点击同意充值
	{
		if($_SESSION['UserInfo']['secLevel']>4)
		{$User_info = M("User_info");
		$topicid =$User_info->setInc('gezi_num1',"`id_user`=".$id_user,$count); // 用户格子累加
		$topicid1 =$User_info->setInc('own_gezi_num'," `id_user` = ".$id_user,$count); // 用户格子累加
		$rt = setMsg($msgid,'OK');		
		return $topicid;
		}
		else
		dump('你没有权限！');
	}
    
    
 function checkSureCharge($msgid,$id_user,$count)//客服手工确认交易是否已经成交，然后点击同意充值
	{
		if($_SESSION['UserInfo']['secLevel']>4)
		{$User_info = M("User_info");		
		$topicid =$User_info->setInc('cash_deposit'," `id_user` = ".$id_user,$count); // 用户格子累加
		$rt = setMsg($msgid,'OK');		
		return $topicid;
		}
		else
		dump('你没有权限！');
	}    
	/**
	 * getGezis()
	 * 
	 * @return
	 */
	function getGezis(){//获得4个格子数字，以数组返回
	$id_user = $_SESSION['UserInfo']['id'];
	$User_info = D('User_info');
	$role = $User_info->where("id_user = '$id_user'")->find();
	//dump($role);
	$arry= array($role['own_gezi_num'],$role['gezi_num1'],$role['gezi_num2'],$role['gezi_num3']);
	return $arry;
	}
    
    //检查是否足够支付某个数值
    function checkMoneyEnough($count)
    {
     $nowcount = getGezis();
     return ($nowcount[0]>$count);   
        
    }	
 
 	/**
 	 * getPdttpt()
 	 * 
 	 * @return
 	 */
 	function getPdttpt(){//获得投放产品模板
	$id_user = $_SESSION['UserInfo']['id'];
		$tname = 'Prj_tpt'; $Field = 'id_gezi_prj_tpt'; $Asc = ' ASC'; 
		$searchwords="id_user = '$id_user' OR id_user = 0";
		return ShowTable($tname, $Field, $Asc, $searchwords);	
	}

	/**
	 * pay2Sys()
	 * 
	 * @return
	 */
	function pay2Sys($id_user,$count,$pageNum,$geziPerPage,$status=NULL)//密语支付格子，创建项目
	{//先减去user的钱，成功后再添加支付记录
		$describe = '购买格子项目';
		$type = 1;
        
		if((jianqian($id_user,$count)) AND (geziTradeLog($id_user,$count,$describe,$type))  AND ($newprjid =istPrjList($pageNum,$count,$geziPerPage,$status))) {return $newprjid;}
		else 
		return false;
	}
    
	/**
	 * jianqian()
	 * 
	 * @return
	 */
	function jianqian($id_user,$count)//从客户账户减去指定格子数,事先已经判定总共格子数足够支付
	{	$User_info = M("User_info");		
		$role = $User_info->where("id_user = '$id_user'")->find();
        
	if($role['own_gezi_num']<$count)
     {
	 return false;  //dump('指定账户没有足够格子支付项目启动');
     }
     else
     {
   		$numtmp = $role['gezi_num1']-$count;//从金格扣除，>=0，够了否则从银格扣除
		if($numtmp<0)//num1不够
		{
		$numtmp1 = ($role['gezi_num2']+$numtmp);
			if($numtmp1<0)//num1+num2不够
				{
				$ctt = $role['own_gezi_num'] - ($role['own_gezi_num'] - $count);
				$topicid1 =$User_info->setDec('gezi_num1',"`id_user`=".$id_user,$role['gezi_num1']); // num1+num2+num3足够,num1清零
				$topicid2 =$User_info->setDec('gezi_num2',"`id_user`=".$id_user,$role['gezi_num2']); // num1+num2+num3足够,num2清零
				$topicid3 =$User_info->setDec('gezi_num3',"`id_user`=".$id_user,$ctt); // num1+num2+num3足够
                $topicid =$User_info->setDec('own_gezi_num',"`id_user`=".$id_user,$count);	
				return ($topicid1 and $topicid2 and $topicid3 and $topicid);			
				}
			else//num1+num2足够
			{
			$topicid1 =$User_info->setDec('gezi_num1',"`id_user`=".$id_user,$role['gezi_num1']); // num1+num2足够,num1清零
			$tntt = $role['gezi_num2']-($role['gezi_num1']+$role['gezi_num2']-$count);
			$topicid2 =$User_info->setDec('gezi_num2',"`id_user`=".$id_user,$tntt); // num1+num2足够
            $topicid =$User_info->setDec('own_gezi_num',"`id_user`=".$id_user,$count);
			return ($topicid1 and $topicid2 and $topicid);
			}				
		}
		else// num1足够
		{$topicid1 =$User_info->setDec('gezi_num1',"`id_user`=".$id_user,$count); 
         $topicid =$User_info->setDec('own_gezi_num',"`id_user`=".$id_user,$count); // 用户格子总数减去项目格子数           
		return $topicid1 AND $topicid;
		}   
     }	
    }
	
	/**
	 * geziTradeLog()
	 * 
	 * @return
	 */
	function geziTradeLog($id_user,$count,$describe,$type){//插入一条格子交易转移记录
		$Trade_detail = M("Trade_detail");
		$data['id_user'] = $id_user;
		$data['gezi_num'] = $count;
		$data['describe'] = $describe;
		$data['type'] = $type;
								
		$topicid =$Trade_detail->add($data);
		return 	$topicid;		
	
	}
	
	/**
	 * getPrjpdtList()
	 * 
	 * @return
	 */
	function getPrjpdtList($status=NULL,$id_gezi_prj=NULL){
    //获得登录id发布的项目列表，参数是状态，如果登录人是sec5，则全部项目显示
    $mtable = "gezi_prj_pdt";
    $fieldstr = " * ";
    

    $tb1 = "gezi_prj";
    $condition1 = " gezi_prj_pdt.id_gezi_prj = gezi_prj.id_gezi_prj ";
    $ordbyField = " gezi_prj_pdt.id_gezi_prj DESC ";
    $searchwords = ' and 1=1 ';
    $searchwords = isset($status)? " and gezi_prj.status = '$status' ":$searchwords;
    $searchwords = isset($id_gezi_prj)? " and gezi_prj.id_gezi_prj = $id_gezi_prj ":$searchwords;
    
    $id_user = $_SESSION['UserInfo']['id'];//如果是管理员，则可以查看所有人的prjpdt，否则只能查看自己的
    $searchwords = ($_SESSION['UserInfo']['secLevel']>3)? $searchwords: $searchwords.'  and gezi_prj.id_user ='.$id_user;
	$rt = ShowTableM($mtable,$fieldstr,$tb1,$condition1,$ordbyField,$searchwords);
    
	return $rt;
	}
    
   	function getTaskprjpdtList($status=NULL,$id_gezi_task=NULL){
    
   	$id_user = $_SESSION['UserInfo']['id'];
        
    $Model = new Model() ;
    $sqlstr = "	SELECT task_ctime ,productUrl,TpageNum,gezi_prj_pdt.couponTab,id_gezi_prj_pdt,tTgezi,nowGezi,percent,score,gezi_task_prj.id_gezi_prj,gezi_prj.geziPerPage,tCode, prj_pic,pPic,pName,id_user 
    FROM gezi_task_prj
    JOIN gezi_task 
    ON gezi_task.id_gezi_task = gezi_task_prj.id_gezi_task 
    JOIN gezi_prj 
    ON gezi_task_prj.id_gezi_prj = gezi_prj.id_gezi_prj 
    JOIN gezi_prj_pdt 
    ON  gezi_task_prj.id_gezi_prj = gezi_prj_pdt.id_gezi_prj
    WHERE gezi_task_prj.id_gezi_task = $id_gezi_task 
    AND gezi_task.status = '$status' ORDER BY gezi_prj_pdt.id_gezi_prj_pdt ";
    //dump($sqlstr);
    $rt = $Model->query($sqlstr);
    return $rt;
	}
    
    //获得prj信息，返回prjobj
   	function getPrjList($status=NULL,$type=NULL){//获得登录id发布的项目列表，参数是状态
		$id_user = $_SESSION['UserInfo']['id'];
	$tname ='Prj';
	$Field = 'id_gezi_prj';
	$Asc=' ASC ';	
	$searchwords = isset($status)?('status = '."'$status'") :' 1=1 ' ;
    $searchwords = $searchwords .(isset($type)?('and type = '."'$type'") :' and 1=1 ' );
    $searchwords =  $searchwords.'  and id_user ='.$id_user;
    //dump($searchwords);
	$rt = ShowTable($tname, $Field, $Asc, $searchwords);
	Session::set('PrjListOBJ', $rt); //把获得的项目数据对象存储到session
	return $rt;
	} 
    
    //获得加入的task列表，掏钱的一方
    function getTaskList2($status,$type=NULL,$id_gezi_task=NULL,$id_userp=NULL)
    {
   	$id_user = isset($id_userp)?$id_userp:$_SESSION['UserInfo']['id'];
    $c1 = ' gezi_task.id_gezi_task = gezi_task_prj.id_gezi_task';
    $c2 = ' gezi_task_prj.id_gezi_prj = gezi_prj.id_gezi_prj';
    $fieldstr = ' distinct gezi_task.id_gezi_task,task_type,task_ctime,gezi_task.status,gezi_task.TpageNum,tTgezi,nowGezi,percent,gezi_task.score,execTeamCnt,nowPage,nowLoc,gezi_prj.id_user';
    //$fieldstr = $fieldstr . '';
    $sqlstr = ' and 1=1 ';
    $sqlstr = isset($status)?$sqlstr ." and gezi_task.status = '$status'":$sqlstr;
    $sqlstr = isset($id_gezi_task)?$sqlstr ." and gezi_task.id_task = $id_gezi_task":$sqlstr;
    $sqlstr = isset($type)?$sqlstr ." and gezi_task.task_type = '$type'":$sqlstr;
    $sqlstr = isset($id_user)?$sqlstr ." and gezi_prj.id_user = $id_user":$sqlstr;
    

         
    $rtt = ShowTableM('gezi_task_prj',$fieldstr,'gezi_task',$c1,'gezi_task.id_gezi_task',$sqlstr,'gezi_prj',$c2);

    return $rtt;        
    }
    

    //获得task列表，承接任务方
   	function getTaskList($status,$type=NULL,$TpageNum=NULL,$id_gezi_task=NULL,$id_userp=NULL)
    {//获得指定用户参加的所有指定状态的任务
   	$id_user = isset($id_userp)?$id_userp:$_SESSION['UserInfo']['id'];
    $Model = new Model() ;//查询task表和taskmember表的复合要求的记录
    $sqlstr = "	select id_gezi_task,task_type,task_ctime,status,TpageNum,tTgezi,nowGezi,percent,score,execTeamCnt,nowPage,nowLoc,id_team,person_task_count,id_user,person_task_excgezi from gezi_task,gezi_task_member   where gezi_task.id_gezi_task  = gezi_task_member.id_task"; 
    $sqlstr = isset($id_gezi_task)?$sqlstr ." and gezi_task_member.id_task = $id_gezi_task":$sqlstr; 
    $sqlstr = isset($id_user)?$sqlstr ." and gezi_task_member.id_user = $id_user":$sqlstr; 
    $sqlstr = isset($status)?$sqlstr ." and gezi_task.status = '$status'":$sqlstr;
    $sqlstr = isset($TpageNum)?$sqlstr ." and gezi_task.TpageNum >= $TpageNum":$sqlstr;
    $sqlstr = isset($type)?$sqlstr ." and gezi_task.task_type = '$type'":$sqlstr;
    //dump($sqlstr);
    $rt = $Model->query($sqlstr);
    return $rt; 

	}     
    
    //为交换中体获取所有未满格的任务，可选参数是任务张数
    function getTaskAllList($taskpage=NULL)
    {
        $Task =M('Task');
        $wstr = ' percent < 100';
        $wstr = isset($taskpage)?$wstr." and TpageNum = $taskpage":$wstr;
        $rtlist = $Task->where($wstr)->findAll();
        return $rtlist;
        
    }
	
	/**
	 * istPrjList()
	 * 
	 * @return
	 */
	function istPrjList($pageNum,$geziNum,$geziPerPage,$sauts=NULL){//在项目表插入一条创建记录
	$id_user = $_SESSION['UserInfo']['id'];
		$Prj = M("Prj");
        $Prj_pdt = M("Prj_pdt");
		$data['id_user'] = $id_user;
		$data['ctime'] = date("Y-m-d H:i:s");
		$data['pageNum'] = $pageNum;
		$data['geziNum'] = $geziNum;
		$data['geziPerPage'] = $geziPerPage;
		$data['status'] = isset($status)?$status:'beCreated';
        $data['owner'] = $_SESSION['UserInfo']['name'];
        $topicid =$Prj->add($data);        
		for($i=0;$i<$geziPerPage;$i++)
        {
            $data1['id_gezi_prj']= $topicid;
            $tipcid1 = $Prj_pdt->add($data1);
        }		
		return 	($topicid);		
	}
	
//获得实时的secLevel

	/**
	 * getSecLevel()
	 * 
	 * @return
	 */
	function getSecLevel(){
	$id_user = $_SESSION['UserInfo']['id'];
	$User = D('User');
	$role = $User->where("id = '$id_user'")->find();
	return $role['secLevel'];
	}	
	
 /**
  * setSecLevel()
  * 
  * @return
  */
 function setSecLevel($sec)//设置当前用户的seclevel
	{
		$id_user = $_SESSION['UserInfo']['id'];	
		$User = M("User");
		$data['secLevel'] = $sec;//通过认证				
		$topicid =$User->where("id = '$id_user'")->save($data);
        setcookie('secLevel__', $sec, time() + 3600 * 24 * 7, '/');
        return 	$topicid;			
	}	
    
	
 /**
  * addMsg()
  * 
  * @return
  */
 function addMsg($msgs,$from_id_user,$target,$msgkind,$method,$at1=NULL,$at2=NULL,$at3=NULL,$at4=NULL,$at5=NULL)//在消息表写入一条消息，可能是充值申请、卖家认证申请或者各种情况
    {		
        $Msg = M('Msg');
		$data['from_id_user'] = $from_id_user?$from_id_user:$_SESSION['UserInfo']['id'];//如果没指定发件人，则默认当前登录用户
		$data['msgkind'] = $msgkind;	
		$data['msg'] = $msgs;	
		$data['target'] = $target;					
			
		$data['attach1'] = $at1?$at1:NULL;
		$data['attach2'] = $at1?$at2:NULL;
		$data['attach3'] = $at1?$at3:NULL;
		$data['attach4'] = $at1?$at4:NULL;
		$data['attach5'] = $at1?$at5:NULL;						

		$topid = $Msg->add($data);			

		switch ($method)
		{
		case 'ajax':
		  		if($topid){echo ajaxrt('ok',$topid);}
				else{echo ajaxrt('error','写入记录出错！');}
		  break;  
		case 'bs':
		  		return($topid);
		  break;
		default:
		}
    }
  
   function getOldTcode()//todo
  {
    return false;
  } 
  
  function agreePrj($msgid,$param1,$param2=NULL)//批准项目执行，自动系统匹配
  {
        $id_gezi_prj = $param1;
        $Prj = M("Prj");
		$data['status'] = 'beginExec';				
		$topicid =$Prj->where("id_gezi_prj='$id_gezi_prj'")->save($data);    
        $topicid1 = setMsg($msgid,'OK');
        //$topicid2 = joinTask($Prj);
        //return $topicid and $topicid1 and $topicid2;
        return $topicid and $topicid1;
  } 
//添加项目rec，没有项目描述，其他都有
function addPrjrec($geziPerPage,$PageNum,$owner,$id_user,$type,$status)
{
 $data['geziPerPage']  = $geziPerPage;
 $data['PageNum']  = $PageNum;
 $data['owner']  = $owner;
 $data['type']  = $type;
 $data['status']  = $status;
 $data['ctime']  = date('Y-m-d H:i:s');
 $data['gezuNum']  = $PageNum * $geziPerPage;
 $data['id_user']  = $id_user;
 
 $Prj = M('Prj');
 $rt = $Prj->add($data);  
 return $rt; 
}
//添加任务项目表记录
function addTaskprjRec($id_gezi_task,$id_gezi_prj)
{
    $Task_prj = M("Task_prj");
    $data['id_gezi_prj'] =$id_gezi_prj;;
    $data['id_gezi_task'] = $id_gezi_task;        
    $data['fluid'] =  date("YmdHis");  
       
	$topicid =$Task_prj->add($data);
    return $topicid;    
}

//添加项目产品表，只添加空记录,添加次数由count决定
function addPrjpdtRec($id_gezi_prj,$count)
{
 $data['id_gezi_prj'] = $id_gezi_prj;
 $Prj_pdt = M('Prj_pdt');
 $rtt = true;
 for($i=1;$i<=$count;$i++)
 {
   $rt = $Prj_pdt->add($data);
   $rtt = ($rtt and $rt) ;
 }  
 return $rtt;
}

   	function getbbsList($from,$to,$status=NULL){//获得登录id发布的信息列表，参数是状态
		$id_user = $_SESSION['UserInfo']['id'];
	$tname ='Msg';
	$Field = 'id_gezi_msg';
	$Asc=' DESC ';	
	$searchwords = strlen($status)>0?('status = '."'$status'") :' 1=1 ' ;
    $searchwords =  strlen($from)>0?$searchwords.'  and from_id_user ='.$from:$searchwords;
    $searchwords =  strlen($to)>0?$searchwords.'  and target ='.$to:$searchwords;
	$rt = ShowTable($tname, $Field, $Asc, $searchwords);
    //dump($rt);
	return $rt;
	} 
    
   //发群发消息给指定的团队id下的团队
   function sendTeamMsg($sTeamid,$msg,$from,$kind,$method,$at1=NULL,$at2=NULL,$at3=NULL,$at4=NULL,$at5=NULL){
     //获得分数最高的团队，发消息给此团队所有成员，让他们提交自己承诺分发的张数，不超过10天内的能力
     $Team_member = M('Team_member');
     $recsm = $Team_member->where('id_gezi_team='.$sTeamid)->findAll();
     $cnmt = count($recsm);     
        
     for($i=0;$i<$cnmt;$i++)//群发给分最高的团队所有成员消息
     {
        $topid1 = addMsg($msg,$from,$recsm[$i]['id_user'],$kind,$method,$at1,$at2,$at3,$at4,$at5);        
     }
     return $topid1;
    
   }
//减去个人当前投放能力,数量为承诺接受任务张数
 function setPersonNCapcity($type,$my_task_count,$id_user)
 {
       $User_info = M('User_info');
   		switch ($type)
		{
		case 'dec':
            {
                $rt =  $User_info->setDec('person_now_capcity',' id_user = '.$id_user,$my_task_count);
                $newnow = $_SESSION['UserInfo1']['person_now_capcity']-$my_task_count;
                $_SESSION['UserInfo1']['person_now_capcity'] = $newnow;
                setcookie('person_now_capcity__', $newnow, time() + 3600 * 24 * 7, '/');
            }
            
		  break;  
		case 'inc':
		  	$rt =  $User_info->setInc('person_now_capcity',' id_user = '.$id_user,$my_task_count);
                $newnow = $role1['person_now_capcity']+$my_task_count;
                setcookie('person_now_capcity__', $newnow, time() + 3600 * 24 * 7, '/');            
		  break;
		default:
		} 
        return $rt;
 }
 
 function setTeamNCaocity($type,$taskpage,$id_team)
 {
           $Team = M('Team');
   		switch ($type)
		{
		case 'dec':
            {
                $rt =  $Team->setDec('now_capcity',' id_gezi_team = '.$id_team,$taskpage);
                $_SESSION['UserInfo2']['now_capcity']= $_SESSION['UserInfo2']['now_capcity'] - $taskpage;
            }
            
		  break;  
		case 'inc':
		  	$rt =  $Team->setInc('now_capcity',' id_gezi_team = '.$id_team,$taskpage);
              $_SESSION['UserInfo2']['now_capcity']= $_SESSION['UserInfo2']['now_capcity'] + $taskpage;  
		  break;
		default:
		} 
        return $rt;        
        
 }
 
 //获得个人当前投放能力
 function getPersonNcacity($id_user)
 { $User_info = M('User_info');
    $rt = $User_info->where(' id_user = '.$id_user)->find();
    return $rt['person_now_capcity'];  
 }
 //任务执行团队成员表,和任务团队默认成员不一定相同
function addTask_mem($id_user,$id_team,$id_task,$my_task_count,$person_excgezi)
{
  $Task_member = M('Task_member');
  $data['id_task'] =$id_task;
  $data['id_team'] =$id_team;
  $data['id_user'] =$id_user;
  $data['person_task_count'] =$my_task_count;
  $data['person_task_excgezi'] =$person_excgezi;
  
  $data['applytime'] =Date('Y-m-d H:i:s');  
  $rt =  $Task_member->add($data);
  return $rt;
}


//查询个人是否在task中有未完成任务


//添加团队成员记录
function addTeam_mem($id_user,$id_team)
{
  $Team_member = M('Team_member');
  $data['id_gezi_team'] =$id_team;
  $data['id_user'] =$id_user;
  
  $data['jointime'] =Date('Y-m-d H:i:s');  
  $rt =  $Team_member->add($data);
  return $rt;
}


////更新任务可认领张数,检查任务张数是否已经被认领完毕,完毕后进入印刷
function checkTaskMG($id_task,$count){
    $npage = getTasknPage($id_task);
   if($npage>=$count) //可认领数量大于申请数量
   {
    $Task = M('Task');
    $rt =  setTasknPage('dec',$id_task,$count);
    if($npage==$count)//任务领取完毕
    {
        $data['status'] = 'Printing';
         $Task->where(' id_task = '.$id_task)->save($data);
         execTask($id_task,'Printing');
    }
     return $rt;
   }
   else
   {return false;}
}

//设置当前可认领的page数
function setTasknPage($type,$id_task,$count){
       $Task = M('Task');
   		switch ($type)
		{
		case 'dec':
            {
                $rt =  $Task->setDec('nowPage',' id_gezi_task = '.$id_task,$count);
                return $rt;
                
            }
            
		  break;  
		case 'inc':
		  	$rt =  $Task->setInc('nowPage',' id_gezi_task = '.$id_task,$count);
            return $rt;
		  break;
		default:
		}  
        return $rt;   
}
//获得当前任务的page数(可认领的)
function getTasknPage($id_task){
    $Task = M('Task');
    $rt =  $Task->where(' id_gezi_task = '.$id_task)->find();
    return $rt['nowPage'];
}

//根据id和状态,执行任务的队员步骤 todo
function  execTask($id_task,$status)
{
    $Task = M('Task');
    switch ($status)
		{
		case 'Printing':
            {
            addMsg('任务申请印刷','System','System','taskPrtingApply','bs','id_task:'.$id_task);
            //给印刷厂发消息,让他们印刷,目前是发给系统
            }
		  break;  
		case 'Sending':
		  	
		  break;  
		case 'Getting':
		  	
		  break;  
		case 'Expressing':
		  	
		  break;  
		case 'Full':
		  	$rt =  $Task->where(' id_task = '.$id_task)->setInc('nowPage',$count);
		  break;
		default:
		}  
  }//基础评分机制,对会员评分,目前是根据参数,自动评分,以追加形式,可以更新后继续评分,所有提供的参数,都需要人工和对后提交
  function scoreMember()
  {
		$score = 0;
          switch ($method)
		{
		case 'ajax':
		  		if($topid){echo ajaxrt('ok',$topid);}
				else{echo ajaxrt('error','写入记录出错！');}
		  break;  
		case 'bs':
		  		return($topid);
		  break;
		default:
		}
        return $score;   
  } 
  //基础评分机制
  function scoreTeam($teamtype)
  {
  		$score = 0;
          switch ($teamtype)
		{
		case 'ajax':
		  		if($topid){echo ajaxrt('ok',$topid);}
				else{echo ajaxrt('error','写入记录出错！');}
		  break;  
		case 'bs':
		  		return($topid);
		  break;
		default:
		}
        return $score;  
  } 
  
  //给任务评分,评分用于优先安排任务印刷\投放等资源排序
  function scoreTask($tasktype)
  {
    $score = 0;
          switch ($tasktype)
		{
		case 'ajax':
		  		if($topid){echo ajaxrt('ok',$topid);}
				else{echo ajaxrt('error','写入记录出错！');}
		  break;  
		case 'bs':
		  		return($topid);
		  break;
		default:
		}
        return $score;    
  }
  //获得队员分数,分数由基础评分和交易记录\发展会员\活跃度组成
  function getMemberScore()
  {
    
    
  }
  //获得团队分数,分数由基础评分和交易记录\发展会员\活跃度组成
  function getTeamScore($type)
  {
    
  }
  
  //获得team的成员列表的相关信息  
  function getMemberlist($id_gezi_team){
    $mdl = new Model();
    $sqlstr ="SELECT  gezi_team_member.id_gezi_team,team_name,name_leader, shop_url,coreProduct,category,add_loc,gezi_team_member.jointime,id,gezi_user.city,gezi_user.zip_code,name,person_capcity,person_score,person_now_capcity
                FROM gezi_team_member
                JOIN gezi_user
                ON gezi_team_member.id_user = gezi_user.id
                JOIN gezi_team 
                ON gezi_team.id_gezi_team = gezi_team_member.id_gezi_team
                JOIN gezi_user_info
                ON gezi_team_member.id_user = gezi_user_info.id_user
                WHERE gezi_team.id_gezi_team = $id_gezi_team;"; 
    $rt = $mdl->query($sqlstr);   
    return $rt; 
  }
  
  //获得团队当前投放能力
  function getTeamNcacity($team_id)
  {
    $Team = M('Team');
    $rt = $Team->where(' id_gezi_team = '.$team_id)->find();
    return $rt['now_capcity'];    
  }
  
  
  //判断任务成员表中是否存在该id
  function isExistTaskMember($id_user,$id_task)
  {
   $Task_member = M('Task_member');
   $rt = $Task_member->where('id_user = '.$id_user.' and id_task='.$id_task)->find();
   //dump($rt);
   return count($rt); 
  }
  
  function getUser_info() 
  {   $User_info = M('User_info');
  $id_user = $_SESSION['UserInfo']['id'];
   $rt = $User_info->where('id_user = '.$id_user)->find();
    return $rt;
  }
  
    function getUser($id=NULL) 
  {   $User = M('User');
  $id_user = isset($id)?$id:$_SESSION['UserInfo']['id'];
   $rt = $User->where('id = '.$id_user)->find();
    return $rt;
  }

//新队员增加后累加队员的的得分、能力到团队，团队队员数量自增
//自减同上
 function upTeamCapSco($type,$id_team,$id_user,$capcity,$score)
 {
         $Team = M('Team');
   		switch ($type)
		{
		case 'dec':
            {
                $rt1 =  $Team->setDec('team_capcity',' id_gezi_team = '.$id_team,$capcity);
                $rt2 =  $Team->setDec('team_score',' id_gezi_team = '.$id_team,$score);
                $rt3 =  $Team->setDec('now_capcity',' id_gezi_team = '.$id_team,$capcity);
                $rt4 =  $Team->setDec('member_num',' id_gezi_team = '.$id_team);
                $rt =($rt1 and $rt2 and $rt3 and $rt4);
            }
            
		  break;  
		case 'inc':
		  	$rt1 =  $Team->setInc('team_capcity',' id_gezi_team = '.$id_team,$capcity);
            $rt2 =  $Team->setInc('team_score',' id_gezi_team = '.$id_team,$score);
            $rt3 =  $Team->setInc('now_capcity',' id_gezi_team = '.$id_team,$capcity);
            $rt4 =  $Team->setInc('member_num',' id_gezi_team = '.$id_team);
            $rt =($rt1 and $rt2 and $rt3 and $rt4);
		  break;
		default:
		} 
        
  return $rt;
 }
//生成邀请注册地址
function getRegUrl()
{
    $name = $_SESSION['UserInfo']['name'];
    $id = $_SESSION['UserInfo']['id'];
    $url = 'http://'.$_SERVER["HTTP_HOST"].__APP__.'/AuthACL/reg?id='.$id.'&code='.md5($name);
    return $url;
}

//获得荣誉列表
function getHonorlist()
{
 $id = $_SESSION['UserInfo']['id'];
 $id_team = $_SESSION['UserInfo']['team_id'];
 $Honor = M('Honor');
 $rt = $Honor->where('id_user='.$id .' and id_team='.$id_team)->findAll();
 return   $rt;    
}

//建立一个新任务
function createTaskRec($tasktype,$taskpage,$mypage,$geziPp,$id_team)
{
  $Task = M('Task');
  $data['task_type']=$tasktype;
  $data['task_ctime']=date('Y-m-d H:i:s');
  $data['status']='Adding';
  $data['TpageNum']=$taskpage;
  $data['tTgezi']=$taskpage * 24;
  $data['nowGezi']=$geziPp;//新创建任务起始被占位的格子
  $data['percent']=($taskpage * $geziPp)/$data['tTgezi'];//商品占位百分比,需要计算
  $score = scoreTask($tasktype);
  $data['execTeamCnt']=1;
  $data['nowPage']=$taskpage-$mypage;
  $data['id_team'] = $id_team;
  $data['nowLoc'] = 24-$geziPp;
  $data['id_team'] = $id_team; 
    
  $rt = $Task->add($data);  
  return $rt; 
}

//知道prjid和task原来nowGezi,为prjpdt的所有pdt的couponTab赋值
function setPrjPdtCouponTab($nowGezi,$id_gezi_prj)
{
     $rt = true;
     $Prj_pdt = M('Prj_pdt');
     $pdts = $Prj_pdt->where(" id_gezi_prj = ".$id_gezi_prj)->findAll();
     $pdtcount = count($pdts);
     for($i=1;$i<=$pdtcount;$i++)
     {
      $id_gezi_prj_pdt = $pdts[$i-1]['id_gezi_prj_pdt'];
      $data['couponTab'] = $nowGezi +$i;  
      $tr = $Prj_pdt->where(" id_gezi_prj_pdt = ".$id_gezi_prj_pdt)->save($data);
      $rt = $rt and $tr;
     }   
 return $rt;
}
?>